/*
 * SerialFile.cpp
 *
 *  Created on: Oct 3, 2009
 *      Author: Abraham
 */

#include "serialfile.h"

SerialFile::SerialFile(const string& file, SerialPort::BaudRate baud)
{
	serialPortFile = file;
	baudRate = baud;
	openSerialPort(serialPortFile, baudRate);
}

SerialFile::SerialFile()
{
	serialPortFile = "/dev/ttyUSB0";
	baudRate = SerialPort::BAUD_115200;
}

SerialFile::~SerialFile()
{
	if( serialPort->IsOpen())
		serialPort->Close();
}

void SerialFile::openSerialPort(const string& file, SerialPort::BaudRate baud)
{
	std::cout << "Serial port (opening): " << file << std::endl;

		// call SerialPort Constructor
		serialPort = new SerialPort( file );

		try
		{
			serialPort->Open(baud, SerialPort::CHAR_SIZE_DEFAULT,
					SerialPort::PARITY_DEFAULT, SerialPort::STOP_BITS_DEFAULT,
					SerialPort::FLOW_CONTROL_DEFAULT);

			std::cout << "Serial port: " << file << " opened successfully" << std::endl;
		}
		catch(exception &e)
		{
			std::cout << e.what() << std::endl;
		}
}

string SerialFile::getSerialData()
{
	if( serialPort->IsOpen() )
	{
		string buffer;

		try
		{
			buffer = serialPort->ReadLine(40,0x0D);

			while( serialPort->IsDataAvailable() )
				serialPort->ReadLine(5,0x0D);
		}
		catch( exception &e )
		{
			//std::cout << e.what() << std::endl;
		}
		return buffer;
	}
	else
	{
		openSerialPort(serialPortFile, baudRate);

		return "";
	}
}

void SerialFile::writeSerialData(string buffer)
{
	if( serialPort->IsOpen() )
	{
		try
		{
			serialPort->Write(buffer);
		}
		catch( exception &e )
		{
			std::cout << e.what() << std::endl;
		}
		return;
	}
	else
	{
		openSerialPort(serialPortFile, baudRate);

		return;
	}
}
